﻿using Magicodes.Mvc.AuditFilter;
using Magicodes.Mvc.RoleMenuFilter;
using Magicodes.WeiChat.Data.Models;
using Magicodes.WeiChat.Data.Models.CMS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using System.Threading.Tasks;
using System.Net;
using Magicodes.WeiChat.Infrastructure.MvcExtension.Ajax;
using System.Data.Entity;

namespace Magicodes.WeiChat.Controllers.WeChat.CMS
{
    [RoleMenuFilter("CMS管理", "{A25A207A-B6DA-470A-B8BC-3BFF5C955666}", "Admin",
         iconCls: "fa fa-list-alt")]
    public class Column_ManageController : TenantBaseController<WeiChat_KFCInfo>
    {
        [AuditFilter("栏目管理列表", "{056411E3-5988-4D62-BAF8-AD41F6CB6DD3}")]
        [RoleMenuFilter("栏目管理", "{056411E3-5988-4D62-BAF8-AD41F6CB6DD3}", "Admin",
             url: "/Column_Manage", parentId: "{A25A207A-B6DA-470A-B8BC-3BFF5C955666}")]
        // GET: Column_Manage/Index
        public ActionResult Index(string q, int pageIndex = 1, int pageSize = 10)
        {
            var queryable = db.Column_Manages.AsQueryable();
            if (!string.IsNullOrWhiteSpace(q))
            {
                queryable = queryable.Where(p => p.ColumName.Contains(q));
            }
            var pagedList = new PagedList<Column_Manage>(
                             queryable.OrderByDescending(p => p.CreateTime)
                             .Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(),
                             pageIndex, pageSize, queryable.Count());
            return View(pagedList);
        }

        // GET: Column_Manage/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Column_Manage/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public async Task<ActionResult> Create([Bind(Include = "ColumName,IsOnePage,OnePageContent,IsShow,Intro,Autor")] Column_Manage column_Manage)
        {
            if (ModelState.IsValid)
            {
                if (db.Column_Manages.Any(p => p.TenantId == TenantId && p.ColumName == column_Manage.ColumName))
                {
                    ModelState.AddModelError("ColumName", "栏目名称重复，请重新输入！");
                    return View(column_Manage);
                }
                SetModel(column_Manage,default(long));
                db.Column_Manages.Add(column_Manage);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View();
        }

        // GET: Column_Manage/Edit
        [HttpGet]
        public ActionResult Edit(long id)
        {
            var cf = db.Column_Manages.FirstOrDefault(p => p.Id == id);
            if (cf == null)
            {
                ModelState.AddModelError("", "该账号不存在！");
            }
            else
            {
                var addModel = new Column_Manage()
                {
                    ColumName=cf.ColumName,
                    IsOnePage=cf.IsOnePage,
                    IsShow=cf.IsShow,
                    Intro=cf.Intro,
                    Autor=cf.Autor
                };
                return View(addModel);
            }
            return View(new Column_Manage());
        }
        
        
        [HttpPost]
        public ActionResult Edit(long id, Column_Manage model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var cf = db.Column_Manages.First(p => p.Id == id);
            cf.ColumName = model.ColumName;
            cf.IsOnePage = model.IsOnePage;
            cf.IsShow = model.IsShow;
            cf.Intro = model.Intro;
            cf.UpdateTime = DateTime.Now;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        // POST: Log_Audit/Delete/5
        // GET: Site_Article/Delete/5
        public async Task<ActionResult> Delete(long? id)
        {
            var ajaxResponse = new AjaxResponse();
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Column_Manage column_Manage = await db.Column_Manages.FindAsync(id);
            var cf = db.Article_Manages.Where(p => p.ColumnId == column_Manage.Id);
            if (cf != null)
            {
                ajaxResponse.Success = false;
                ajaxResponse.Message = "存在关联信息不允许删除！";
                return Json(ajaxResponse);
            }
            else
            {
                db.Column_Manages.Remove(column_Manage);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }

        //
        // GET: Column_Manage/EditContent
        public async Task<ActionResult> EditContent(long id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Column_Manage column_Manage = await db.Column_Manages.FindAsync(id);
            if (column_Manage == null)
            {
                return HttpNotFound();
            }
            return View(column_Manage);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]        
        [ValidateInput(enableValidation: false)]
        public async Task<ActionResult> EditContent([Bind(Include = "Id,ColumName,IsOnePage,OnePageContent,IsShow")] Column_Manage column_Manage)
        {
            if (ModelState.IsValid)
            {
                Column_Manage columnManage  = db.Column_Manages.Find(column_Manage.Id);                
                columnManage.OnePageContent = column_Manage.OnePageContent;                
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(column_Manage);
        }

        // POST: Column_Manage/BatchOperation/{operation}
        /// <summary>
        /// 批量操作
        /// </summary>
        /// <param name="operation">操作方法</param>
        /// <param name="ids">主键集合</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Column_Manage/BatchOperation/{operation}")]
        public async Task<ActionResult> BatchOperation(string operation, params long[] ids)
        {
            var ajaxResponse = new AjaxResponse();
            if (ids.Length > 0)
            {
                try
                {
                    var models = await db.Column_Manages.Where(p => ids.Contains(p.Id)).ToListAsync();
                    if (models.Count == 0)
                    {
                        ajaxResponse.Success = false;
                        ajaxResponse.Message = "没有找到匹配的项，项已被删除或不存在！";
                        return Json(ajaxResponse);
                    }
                    switch (operation.ToUpper())
                    {
                        case "DELETE":
                            #region 删除
                            {
                                db.Column_Manages.RemoveRange(models);
                                await db.SaveChangesAsync();
                                ajaxResponse.Success = true;
                                ajaxResponse.Message = string.Format("已成功操作{0}项！", models.Count);
                                break;
                            }
                        #endregion
                        default:
                            break;
                    }
                }
                catch (Exception ex)
                {
                    ajaxResponse.Success = false;
                    ajaxResponse.Message = ex.Message;
                }
            }
            else
            {
                ajaxResponse.Success = false;
                ajaxResponse.Message = "请至少选择一项！";
            }
            return Json(ajaxResponse);
        }

    }
}